var city_new = require('../../../utils/city.js');

var requests = require('../../../requests/api.js');

var util = require('../../../utils/util.js');

var cityData_new = city_new.data.RECORDS;

var app = getApp();

var city_s = []; // “市区”集合
var county_s = []; // “县区”集合
var address = ' '; // 地址

var provinceName = '' // 选择省区 -名字
var province_id = ''; // 选择省区 -id

var cityName = '' // 选择市区 - 名字
var city_id = ''; // 选择省区 -id

var countyName = '' // 选择县区 -名字
var county_id = ''; // 选择省区 -id

// 输入字段
var input_name = '';
var input_phone = '';
var input_address = '';

// 所有的 省市区 集合 
var result_province = cityData_new.filter(
  function(value) {
    return (value.level_type == 1);
  }
);
var result_city = cityData_new.filter(
  function(value) {
    return (value.level_type == 2);
  }
);
var result_county = cityData_new.filter(
  function(value) {
    return (value.level_type == 3);
  }
);
// 当前的 省市区 集合
var province_s = result_province
var city_s = [];
var county_s = [];

Page({
  /**
   * 页面的初始数据
   */
  data: {
    title: "",
    // items_name:['1','2','3','4',],
    items: [{
        path: '/pages/order/list/index',
        placeholder: '请输入收货人姓名',
        text_type: 'text',
        title: '收件人',
      },
      {
        path: '/pages/address/list/index',
        placeholder: '请输入收货人手机号',
        text_type: 'number',
        title: '手机号',
      },
      {
        path: '18521708248',
        placeholder: '请选择地区',
        disabled: true,
        title: '省市区',
      },
      {
        path: '/pages/help/list/index',
        placeholder: '请输入详细地址',
        text_type: 'text',
        title: '详细地址',
      }
    ],
    items_text: [],
    settings: [{
      icon: '../../../assets/address/unCheck.png',
      text: '设为默认',
      path: '/pages/about/index'
    }, ],
    isSelect: false, // 是否默认
    isAddAdress: true, // 是否添加界面

    // 城市数据
    provinces: province_s,
    citys: city_s,
    countys: county_s,
    cityValue: [0, 0, 0],
    cityText: '',
    isCity: true, // 是否选择弹出 选择城市
    testData: new Object()
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    var data = this.data;
    new app.WeToast();
    data.isAddAdress = (options.isAdd == "true" ? true : false);

    if (!data.isAddAdress) { // 判断从是编辑 还是 添加， 编辑为 0 

      data.testData = JSON.parse(options.obj); //解析得到对象  

      var obj = data.testData;
      data.items_text = [obj.receiverName, obj.receiverMobile, '', obj.addressDetail]
      data.cityText = obj.provinceName + ' - ' + obj.cityName + ' - ' + obj.countyName;
      data.isSelect = obj.isDefault;

      var province_Index = 0;
      var city_Index = 0;
      var county_Index = 0;
      city_s = [];
      county_s = [];
      //城市
      // 获取省份下标
      for (let i = 0; i < result_province.length; i++) {
        var provinceId = result_province[i].id;
        if (provinceId == obj.provinceId) {
          province_Index = i;
          break;
        }
      }
      // 拿到对应省区的 市区 数据
      city_s = this.selectResultAction(result_city, obj.provinceId);
      // 获取市区下标
      for (let i = 0; i < city_s.length; i++) {
        var cityId = city_s[i].id;
        if (cityId == obj.cityId) {
          city_Index = i;
          break;
        }
      }
      // 拿到对应市区的 县区 数据
      county_s = this.selectResultAction(result_county, obj.cityId);
      // 获取县区下标
      for (let i = 0; i < county_s.length; i++) {
        var countyId = county_s[i].id;
        if (countyId == obj.countyId) {
          county_Index = i;
          break;
        }
      }
      // 记录对应的 picekr 组的下标
      data.cityValue = [province_Index, city_Index, county_Index];

      this.setData({
        items: data.items,
        items_text: data.items_text,
        cityText: data.cityText,
        isSelect: data.isSelect,
      })

    } else {
      //城市
      // 获取第一列元素 -- 北京
      city_s = this.selectResultAction(result_city, 110000);

      county_s = this.selectResultAction(result_county, 110100);

    };
    this.setData({
      provinces: province_s,
      citys: city_s,
      countys: county_s,
      isAddAdress: data.isAddAdress
    });
    this.setData({
      cityValue: data.cityValue
    });
    wx.setNavigationBarTitle({
      title: options.title,
      success: function(res) {}
    })
  },

  /**
   * 当页面滑动到底部时触发的方法,删掉这个方法后控制台会报事件警告
   */
  onReachBottom: function() {},

  // 设置为默认点击事件
  selectRow: function(e) {
    var obj = this.data.testData;
    this.data.isSelect = !this.data.isSelect
    obj.isDefault = this.data.isSelect // 状态取反
    this.loadData()
    this.setData({
      isSelect: this.data.isSelect
    })
  },

  // 点击输入框row
  selectinput: function(e) {
    const index = e.currentTarget.dataset.index
    switch (index) { // 如果为第二个说明为点击地址栏 弹出选择器框
      case 2:
        this.risePicker()
        break
      default:
        break
    }
  },

  //删除地址
  deleteAddress: function(e) {
    const t = this;
    var obj = t.data.testData;
    wx.showModal({
      title: '提示',
      content: '确定要删除?',
      success: function(res) {
        if (res.confirm) { // 点击确定
          t.request_deleteAddress(obj.id)
        } else if (res.cancel) {

        }
      }
    })
  },

  // 重新刷新显示数据
  loadData: function() {
    var obj = this.data.testData;
    this.data.items_text = [obj.receiverName, obj.receiverMobile, '', obj.addressDetail]
    this.setData({
      items_text: this.data.items_text,
    })
  },

  //确认按钮
  sureAction: function(e) {
    const that = this
    var obj = that.data.testData;
    if (typeof(obj.receiverName) == 'undefined' || obj.receiverName == '') {
      this.loadData()
      that.wetoast.toast({
        title: '请输入姓名',
      })
      return
    }
    if (typeof(obj.receiverMobile) == 'undefined' || obj.receiverMobile == '') {
      this.loadData()
      that.wetoast.toast({
        title: '请输入手机号',
      })
      return
    }
    if (!util.checkMobile(obj.receiverMobile)) {
      this.loadData()
      that.wetoast.toast({
        title: '请输入正确的手机号',
      })
      return
    }
    if (that.data.cityText == "") {
      this.loadData()
      that.wetoast.toast({
        title: '请选择省市区',
      })
      return
    }
    if (typeof(obj.addressDetail) == 'undefined' || obj.addressDetail == '') {
      this.loadData()
      that.wetoast.toast({
        title: '请填写详细地址',
      })
      return
    }
    if (!that.data.isAddAdress) { // 判断从是编辑 还是 添加， 编辑为 0 
      that.requst_change(obj)
    } else {
      that.requst_add(obj)
    }
  },

  //请求网络 -- 添加收货地址
  requst_add: function(params) {
    const that = this
    wx.showLoading({
      title: '',
    })
    requests.post_addAddress(params, (res) => {
      that.backPageRefreshData()
    }, (data) => {
      if (util.alertNetworkError(data)) {
        that.wetoast.toast({
          title: data.resMsg,
        })
      }
    }, () => {});
  },

  //请求网络 -- 修改收货地址
  requst_change: function(params) {
    const that = this
    wx.showLoading({
      title: '',
    })
    requests.put_changenAddress(params, (res) => {
      that.backPageRefreshData()
    }, (data) => {
      if (util.alertNetworkError(data)) {
        that.wetoast.toast({
          title: data.resMsg,
        })
      }
    }, () => {});
  },

  // 请求网络 -- 删除地址
  request_deleteAddress: function(id) {
    const that = this;
    wx.showLoading({
      title: '',
    })
    requests.delete_address(id, (res) => {
      that.refresh_addressList()
      this.backPage()
    }, (data) => {
      if (util.alertNetworkError(data)) {
        that.wetoast.toast({
          title: data.resMsg,
        })
      }
    }, () => {

    });
  },

  // 刷新地址列表页数据
  refresh_addressList: function() {
    var pages = getCurrentPages() // 获取当前栈里面页面
    var prevPage = pages[pages.length - 2] //上一个页面
    prevPage.requestListData()
  },

  // 返回上个界面 刷新地址列表的数据
  backPageRefreshData: function() {
    this.refresh_addressList()
    this.backPage()
  },

  // 返回上个界面
  backPage: function() {
    wx.navigateBack({
      delta: 1
    })
  },

  //调起选择器
  risePicker: function() {
    var that = this.data;
    var obj = that.testData;
    that.items_text = [obj.receiverName, obj.receiverMobile, '', obj.addressDetail]
    this.setData({
      items_text: that.items_text,
      isCity: false
    })
  },

  // 监听 input 输入的文本
  bindKeyInput: function(e) {
    var obj = this.data.testData;
    var index = e.currentTarget.dataset.index;
    var str = e.detail.value;
    switch (index) {
      case 0:
        obj.receiverName = str
        break
      case 1:
        obj.receiverMobile = str
        break
      case 3:
        obj.addressDetail = str
        break
      default:
        break
    }
  },

  // 根据指定条件返回 数组
  selectResultAction: function(data, event) {
    var result = data.filter(
      function(value) {
        return (value.parent_id == event);
      }
    );
    return result;
  },

  //城市选择器
  cityChange: function(e) {
    var val = e.detail.value // 改变的picker 每一列对应的下标位置
    var t = this.data.cityValue; // 原本的位置 
    if (val[0] != t[0]) { // 第一列改变
      city_s = [];
      county_s = [];
      var current_id = province_s[val[0]].id;
      city_s = this.selectResultAction(result_city, current_id);
      var current_city_id = city_s[0].id;
      county_s = this.selectResultAction(result_county, current_city_id);
      this.setData({
        citys: city_s,
        countys: county_s,
        cityValue: [val[0], 0, 0]
      })
      return;
    }
    if (val[1] != t[1]) { // 第二列改变
      county_s = [];
      var current_city_id = city_s[val[1]].id;
      county_s = this.selectResultAction(result_county, current_city_id);
      this.setData({
        countys: county_s,
        cityValue: [val[0], val[1], 0]
      })
      return;
    }
    if (val[2] != t[2]) { // 第三列改变
      this.setData({
        county: this.data.countys[val[2]],
        cityValue: val
      })
      return;
    }
  },

  //确定选择
  ideChoice: function(e) {
    var that = this;
    var $act = e.currentTarget.dataset.act;
    var $mold = e.currentTarget.dataset.mold;

    var obj = that.data.testData;
    //城市
    if ($act == 'confirm' && $mold == 'city') {
      var t = this.data.cityValue; // 原本的位置 
      // 记录当前选择的省市区ID  
      obj.cityId = city_s[t[1]].id;
      obj.countyId = county_s[t[2]].id;
      obj.provinceId = province_s[t[0]].id;

      obj.provinceName = province_s[t[0]].name;
      obj.cityName = city_s[t[1]].name;
      obj.countyName = county_s[t[2]].name;

      that.cityText = obj.provinceName + ' - ' + obj.cityName + ' - ' + obj.countyName
      that.setData({
        cityText: that.cityText
      })
    }
    that.setData({
      isCity: true
    })
  }
})